#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <sys/wait.h>

// 日志文件名
#define LOG_FILE "process_test.log"

// 日志函数
void log_message(const char *message) {
    FILE *log_file = fopen(LOG_FILE, "a");
    if (log_file == NULL) {
        perror("Failed to open log file");
        exit(EXIT_FAILURE);
    }
    time_t now = time(NULL);
    char *time_str = ctime(&now);
    if (time_str != NULL && strlen(time_str) > 0) {
        time_str[strlen(time_str) - 1] = '\0';  // 去掉换行符
    }
    fprintf(log_file, "%s - %s\n", time_str, message);
    fclose(log_file);
}

// 进程函数
void process_function(const char *name) {
    for (int i = 0; i < 10; ++i) {
        sleep(1);  // 休眠1秒
        log_message(name);
    }
}

int main() {
    // 清空或创建日志文件
    FILE *log_file = fopen(LOG_FILE, "w");
    if (log_file == NULL) {
        perror("Failed to create log file");
        exit(EXIT_FAILURE);
    }
    fclose(log_file);

    pid_t pid = fork();

    if (pid < 0) {
        perror("Failed to fork");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {
        // 子进程
        process_function("Child process wake up");
        exit(EXIT_SUCCESS);
    } else {
        // 父进程
        process_function("Parent process wake up");

        // 等待子进程结束
        wait(NULL);

        log_message("All processes completed. Exiting program.");
    }

    return 0;
}
